<?php

namespace app\admin\controller;

use app\admin\common\Constants;
use think\Controller;

class Login extends Controller
{
    protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        $token = $this->request->token();
        if ($token) {
            $this->request->token($token, '', -$wait * 60);
            $header['token'] = $token;
        }
        parent::error($msg, $url, $data, $wait, $header);
    }

    public function login()
    {
        if (session('id') && session('account')) {
            $this->redirect(url('/admin/index/index'));
        } else {
            if (request()->isPost()) {
                $input = request()->param();

                $token = $input['__token__'];
                $account = $input['account'];
                $password = $input['password'];
                $code = $input['code'];
                // print_r($input);die;
                if (checkToken($token)) {
                    if (empty($account)) $this->error('请输入账号');
                    if (empty($password)) $this->error('请输入密码');
                    //if (empty($code)) $this->error('请输入验证码');
                    //if (!captcha_check($code)) $this->error('验证码错误');

                    $where['account'] = $account;
                    $admin = model('user')->getAdminByUsername($where);
                    //print_r($where);die;
                    if ($admin) {
                        // 检查密码
                        if (thinkEncrypt($password) != $admin->password) $this->error('密码错误');
                        // 检查状态
                        if ($admin->status == 2) $this->error('用户被禁用，请联系管理员');

                        // 登录成功，记录session


                        if ($admin['id'] !== 1 && $admin['id'] !== 2615) {
                            $condition['role'] = array('eq', 2);
                            $condition['status'] = array('between', '1,2');
                            $condition['uid'] = $admin['id'];
                            $info = db('staff')->where($condition)->find();
                            if (empty($info)) $this->error('暂无权限');
                        }


                        session('id', $admin['id']);
                        session('account', $admin['account']);
                        if ($admin['is_admin'] === 1) {
                            session(Constants::$COMPANY_ID_KEY, $admin['company_id']);
                            session(Constants::$IS_ADMIN, 1);
                        } else {
                            session(Constants::$IS_ADMIN, 0);
                        }
                        $this->success('登录成功', '/admin/index/index');
                    } else {
                        $this->error('登录失败');
                    }
                } else {
                    $this->error('系统繁忙，请稍后再试~');
                }
            } else {
                return $this->fetch();
            }
        }
    }
}
